import React, { PureComponent } from 'react';
import { Icon, Table, TreeSelect, Button, Form, notification } from 'antd';
import { connect } from 'dva';
import { worker } from "../../utils/worker"
import "./form.less"
import "../../Common.less"
class BotComponentForm extends PureComponent {
    constructor(props) {
        super(props);
        this.state = {
            mass: false,
            spanId: null,
            treeData: [],
            originalData: [],
            selectActive: true,
            bridgeList: [],
            selectedRowKeys: [],
            data: [],
            count: 0,
            name: "",
            columns: [],
            allChecked: false,
            st: null,
            qString: "",
            pagination: {
                pageSize: 5,
                pageNum: 1
            },
            loading: false,
            total: 0,
        }
        this.getData = this.getData.bind(this);
        this.editComponent = this.editComponent.bind(this);
        this.onSelect = this.onSelect.bind(this)
        this.onSelectChange = this.onSelectChange.bind(this)
        this.onConfirm = this.onConfirm.bind(this)
        this.refresh = this.refresh.bind(this)
        this.massEditProps = this.massEditProps.bind(this)
        this.massEditProps2 = this.massEditProps2.bind(this)

    }

    editComponent(e, item) {
        let { operateType, bridgeId, selectedRowKeys } = this.state;
        this.setState({
            mass: false,
            spanId: item.id
        })
        if (this.props.modalContext) {
            this.props.modalContext.updateModal({
                visible: true,
                title: "选择构件",
                event: { code: "structureSelect" },
                extra: {
                    "nodeType": 4,
                    operateType: 'cusProps',
                    selectionOrSpanIds: [item.id],
                    definitionIds: selectedRowKeys,
                    bridgeId,
                    ids:item.definitionIds?item.definitionIds:[],
                    type: "bottom",
                    spanType: item.spanType
                }
            });
        }
    }
    async getData() {
        this.setState({
            loading:true
        })
        const { structureTree,getBotStructuresByBridge } = this.props;
        let { selectAll, selectedRowKeys, sid } = this.state;
        let { bridgeId } = this.state;
        if(!bridgeId){
            return;
        }
        let res = await getBotStructuresByBridge({ bridgeId, sid })
        let extra = {};
        if (res && res.rows && res.rows.length) {
            const len=res.rows.length;
            for (let i = 0; i < len; i++) {
                const item = res.rows[i];
                if (item.definitionTreeIds && item.definitionTreeIds.length) {
                    let arr = []
                    const len2=item.definitionTreeIds.length
                    for (let i = 0; i < len2; i++) {
                        let item2 = item.definitionTreeIds[i];
                        const obj = await worker.getTreeNode(structureTree, item2)
                        arr.push({
                            definitionTreeId: item2,
                            title: obj.title,
                            code: obj.code
                        })
                    }
                    item.structures = arr;
                }
                item.checked = false;
                item.edit = false;
                if (selectAll) {
                    selectedRowKeys.push(item.id)
                }
            }
            extra.selectedRowKeys = selectedRowKeys
            this.setState({
                loading: false,
                selectAll: false,
                originalData: res ? res.rows : [],
                data: res ? res.rows : [],
                total: res ? res.total : 0,
                ...extra
            })
        } else {
            this.setState({
                loading: false,
                originalData: [],
                data: [],
                total: 0
            })
        }
    }
    onConfirm(params) {
        return new Promise((resolve, reject) => {
            const {treeContext,addDefinitionInstance}=this.props;
            let selectionOrSpanIds = []
            let { selectedRowKeys, data, bridgeId, operateType } = this.state;
            if (data && data.length) {
                if (selectedRowKeys && selectedRowKeys.length) {
                    const len=data.length;
                    const len2=selectedRowKeys.length;
                    for (let i = 0; i < len; i++) {
                        let item = data[i];
                        for (let j = 0; j < len2; j++) {
                            let item2 = selectedRowKeys[j];
                            if (item.id == item2) {
                                selectionOrSpanIds.push(item.id)
                            }
                        }
                    }
                }

            }

            addDefinitionInstance({
                operateType: operateType || "cover",
                selectionOrSpanIds,
                definitionIds: selectedRowKeys,
                bridgeId,
                "type": "bottom"
            }, res => {
                if (res && res.length) {
                    const len=res.length;
                    for (let i = 0; i < len; i++) {
                        let obj = res[i];
                        if (obj.data && obj.data.length) {
                            const len2=obj.data.length;
                            for (let i = 0; i < len2; i++) {
                                let unit = obj.data[i];
                                let { definitionInstances, selectionOrSpanId } = unit;
                                if (definitionInstances && definitionInstances.length) {
                                    const len3= definitionInstances.length
                                    for (let i = 0; i < len3; i++) {
                                        let item = definitionInstances[i];
                                        item.title = item.instanceName;
                                        item.key = 'botStructureComponentUnit' + item.id;
                                        item.type = "bottom"
                                        item.eventType = 'botStructureComponentUnit'
                                        item.eventKey = 'botStructureComponentUnit'
                                        item.checkable = true
                                        item.selectable = true
                                        item.isLeaf = true
                                    }
                                }
                                // botStructureDirec
                                if (operateType && operateType == "add") {
                                    treeContext.insertTreeNode("botStructureDirec" + selectionOrSpanId, definitionInstances)

                                } else {
                                    treeContext.updateTreeNode("botStructureDirec" + selectionOrSpanId, definitionInstances)

                                }
                            }
                        }

                    }
                }

                resolve()
            }, err => {
                reject()
            })
        })
    }
    refresh() {
        this.setState({
            selectedRowKeys:[]
        })
        this.getData()
    }
    async editComponentProps(e,item){
        e.preventDefault()
        let { bridgeId, data } = this.state;
        const {modalContext,getBottomProperty}=this.props;
        const selectedRowKeys=[item.id]
        if (!bridgeId) {
            notification.warn({ message: "请选择桥梁!" })
            return;
        }
        if (!selectedRowKeys || !selectedRowKeys.length) {
            notification.warn({ message: "至少选择一个布跨!" })
            return;
        }
        let arr = [], arr2 = [],arr3=[],arr4=[];
        if (selectedRowKeys && selectedRowKeys.length) {
            const len=selectedRowKeys.length
            for (let i = 0; i < len; i++) {
                let item = selectedRowKeys[i];
                let obj = data.find(item2 => item2.id == item)
                if(!obj.definitionIds){
                    notification.warn({ message: "请先添加构件!" })
                    return;
                }
                arr.push(obj.stype)
                arr2.push(obj.definitionIds)
                arr3.push(...obj.definitionIds)
                arr4.push(...obj.definitionInstanceIds)
            }
        }
        arr = Array.from(new Set(arr))
        if (arr.length && arr.length > 1) {
            notification.warn({ message: "不能同时选择桥墩和桥台!" })
            return;
        }
        const isAllSame=!arr2.some(function (item, index) {
            return item.toString() !== arr2[0].toString();
        });
        if(!isAllSame){
            notification.warn({ message: "只能选择同类构件!" })
            return;
        }
        let selectionOrSpanIds = []
        if (data && data.length) {
            if (selectedRowKeys && selectedRowKeys.length) {
                const len=data.length;
                for (let i = 0; i < len; i++) {
                    let item = data[i];
                    const len2=selectedRowKeys.length
                    for (let j = 0; j < len2; j++) {
                        let item2 = selectedRowKeys[j];
                        if (item.id == item2) {
                            selectionOrSpanIds.push(item.id)
                        }
                    }
                }
            }

        }
        let res2 = await getBottomProperty({
            definitionIds: Array.from(new Set(arr3)),
            definitionInstanceIds: arr4,
            type:"bottom"
        })
        if (res2&&res2.length&&modalContext) {
            modalContext.updateModal({
                visible: true,
                title: "自定义属性编辑",
                event: { code: "cusTable",width:1200 },
                extra:{
                    designedStructures:res2,
                    type:"bottom"
                }
            });
        }else{
            notification.warn({ message: "未设置属性!" })
        }
    }
    async componentDidMount() {
        let { project, bridgeData, reset, currentBridge,bridgeMainAndChild,onLoaded } = this.props;
        if ((bridgeData || currentBridge) && !reset) {
            const curBri = bridgeData || currentBridge
            await this.setState({
                selectedRowKeys: curBri.selectedRowKeys || [],
                operateType: curBri.operateType || "",
                sid: curBri.sid || "",
                selectAll: curBri.selectAll || "",
                bridgeId: curBri.bridgeId || curBri.id
            })
            this.getData()
        } else {
            await this.setState({
                selectedRowKeys: [],
                operateType: null,
                sid: null,
                selectAll: null,
                bridgeId: null
            })
        }

        if (onLoaded) {
            onLoaded(this);
        }
        if (bridgeMainAndChild) {
            let res = await bridgeMainAndChild({ projectId: project.id })
            this.setState({
                treeData: res && res.length ? await worker.loopTreeNode4(JSON.parse(JSON.stringify(res).replace(/bridges/g, 'children')),true) : []
            })
        }
        const columns = [
            {
                title: '桩号',
                dataIndex: 'code',
                width: "150px",
            },
            {
                title: '墩号',
                dataIndex: 'name',
                width: "150px",
            },
            {
                title: '构件',
                dataIndex: 'structures',
                render: (text, record) => text && text.length ? text.map((item, index) => <span className="structure" key={'str' + index}>{item.title + ':' + record['instanceNames'][index]}</span>) : ''
            },


            {
                title: '操作',
                key: 'action',
                width: "250px",
                render: (text, record) => <span className="operate"><a onClick={(e) => this.editComponent(e, record)}><Icon type="edit" />&nbsp;设置构件</a><a style={{marginLeft:"5px"}} onClick={(e) => this.editComponentProps(e, record)}><Icon type="edit" />&nbsp;设置属性</a></span>,
            },
        ];
        this.setState({
            columns
        })
    }
    onSelectChange = selectedRowKeys => {
        this.setState({ selectedRowKeys });
    };
    async onSelect(e) {
        await this.setState({
            bridgeId: e
        })
        this.getData()
    }
    async massEditProps2(e) {
        e.preventDefault()
        let { bridgeId, selectedRowKeys, data } = this.state;
        const {getBottomProperty,modalContext}=this.props;
        if (!bridgeId) {
            notification.warn({ message: "请选择桥梁!" })
            return;
        }
        if (!selectedRowKeys || !selectedRowKeys.length) {
            notification.warn({ message: "至少选择一个布跨!" })
            return;
        }
        let arr = [], arr2 = [],arr3=[],arr4=[]
        if (selectedRowKeys && selectedRowKeys.length) {
            const len=selectedRowKeys.length
            for (let i = 0; i < len; i++) {
                let item = selectedRowKeys[i];
                let obj = data.find(item2 => item2.id == item)
                if(!obj.definitionIds){
                    notification.warn({ message: "请先添加构件!" })
                    return;
                }
                arr.push(obj.stype)
                arr2.push(obj.definitionIds)
                arr3.push(...obj.definitionIds)
                arr4.push(...obj.definitionInstanceIds)
       
            }
        }
        arr = Array.from(new Set(arr))
        if (arr.length && arr.length > 1) {
            notification.warn({ message: "不能同时选择桥墩和桥台!" })
            return;
        }
        const isAllSame=!arr2.some(function (item, index) {
            return item.toString() !== arr2[0].toString();
        });
        if(!isAllSame){
            notification.warn({ message: "只能选择同类构件!" })
            return;
        }
        let selectionOrSpanIds = []
        if (data && data.length) {
            if (selectedRowKeys && selectedRowKeys.length) {
                const len=data.length;
                for (let i = 0; i < len; i++) {
                    let item = data[i];
                    const len2=selectedRowKeys.length
                    for (let j = 0; j < len2; j++) {
                        let item2 = selectedRowKeys[j];
                        if (item.id == item2) {
                            selectionOrSpanIds.push(item.id)
                        }
                    }
                }
            }

        }
        let res2 = await getBottomProperty({
            definitionIds: Array.from(new Set(arr3)),
            definitionInstanceIds: arr4,
            type:"bottom"
        })
        if (res2&&res2.length&&modalContext) {
            modalContext.updateModal({
                visible: true,
                title: "自定义属性编辑",
                event: { code: "cusTable",width:1200 },
                extra:{
                    designedStructures:res2,
                    type:"bottom"
                }
            });
        }else{
            notification.warn({ message: "未设置属性!" })
        }
       
    }
    massEditProps(e) {
        e.preventDefault()
        let { bridgeId, selectedRowKeys, data } = this.state;
        const {modalContext}=this.props;
        if (!bridgeId) {
            notification.warn({ message: "请选择桥梁!" })
            return;
        }
        if (!selectedRowKeys || !selectedRowKeys.length) {
            notification.warn({ message: "至少选择一个布跨!" })
            return;
        }
        let arr = [],arr2=[],arr6=[]
        if (selectedRowKeys && selectedRowKeys.length) {
            const len=selectedRowKeys.length;
            for (let i = 0; i < len; i++) {
                let item = selectedRowKeys[i];
                const obj= data.find(item2 => item2.id == item)
                arr6.push(obj.spanType)
            }
        }
        arr = Array.from(new Set(arr))
        if (arr.length && arr.length > 1) {
            notification.warn({ message: "不能同时选择桥墩和桥台!" })
            return;
        }
        this.setState({
            mass: true
        })
        let selectionOrSpanIds = []
        if (data && data.length) {
            if (selectedRowKeys && selectedRowKeys.length) {
                const len=data.length
                for (let i = 0; i < len; i++) {
                    let item = data[i];
                    const len2=selectedRowKeys.length
                    for (let j = 0; j <len2; j++) {
                        let item2 = selectedRowKeys[j];
                        if (item.id == item2) {
                            selectionOrSpanIds.push(item.id)
                            if(item.definitionIds){
                                arr2.push(...item.definitionIds)
                            }
                        }
                    }
                }
            }
        }
        if (modalContext) {
            modalContext.updateModal({
                visible: true,
                title: "构件属性编辑",
                event: { code: "structureSelect" },
                extra: {
                    "nodeType": 4,
                    operateType: 'cusProps',
                    selectionOrSpanIds,
                    definitionIds: selectedRowKeys,
                    bridgeId,
                    sid:Array.from(new Set(arr2)),
                    type: "bottom",
                    spanType: arr6[0]
                }
            });
        }
    }
    render() {
        let { columns, data, loading, selectedRowKeys, selectActive, treeData } = this.state
        const { currentBridge, commondShow } = this.props;
        const { getFieldDecorator } = this.props.form;
        const rowSelection = {
            selectedRowKeys,
            onChange: this.onSelectChange,
        };
        return (
            <div className="absMiddle topComponent">
                <div className="absMiddle sorter">
                    <Form style={{ padding: "15px 15px" }}
                        labelCol={{ span: 5 }}
                        wrapperCol={{ span: 19 }}

                    >
                        <Form.Item style={{alignItems:"center"}} label='桥梁'>
                            {getFieldDecorator('designStage', {
                                rules: [
                                    { required: true, message: '桥梁' }
                                ],
                                initialValue: currentBridge ? (currentBridge.bridgeId ? currentBridge.bridgeId : currentBridge.id) : undefined
                            })(
                                <TreeSelect
                                    showSearch
                                    treeNodeFilterProp="name"
                                    dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                                    placeholder="请选择桥梁"
                                    treeData={treeData}
                                    allowClear
                                    treeDefaultExpandAll
                                    onSelect={this.onSelect}
                                ></TreeSelect>
                            )}
                        </Form.Item>
                        <div className="btnBox">
                        <Button disabled={!selectedRowKeys.length} onClick={e => this.massEditProps(e)} style={{ background: '#1890ff', borderColor: '#1890ff' }} type="primary">批量设置构件</Button>
                            <Button disabled={!selectedRowKeys.length} onClick={e => this.massEditProps2(e)} style={{ background: '#1890ff', borderColor: '#1890ff' }} type="primary">批量设置属性</Button>
                           
                        </div>

                    </Form>

                </div>
                <Table loading={loading} scroll={{ y: commondShow ? 280 : 360 }} className="absMiddle" rowSelection={selectActive ? rowSelection : false} pagination={false} rowKey={record => record.id} loading={loading} columns={columns} dataSource={data} />
            </div>
        );
    }
}

export default connect(
    ({
        dict: { structureTree },
        structure: { classedStructures },
        bridge: { currentBridge }
    }) => {
        return { classedStructures, currentBridge, structureTree };
    },
    dispatch => ({
        addDefinitionInstance: (values, onSuccess, onError) => dispatch({
            type: 'structure/addDefinitionInstance',
            payload: {
                values,
                onSuccess,
                onError
            }
        }),
        getBottomProperty: (values) => dispatch({
            type: 'structure/getBottomProperty',
            payload: values
        }),
        bridgeMainAndChild: (values) => dispatch({
            type: 'bridge/bridgeMainAndChild',
            payload: values
        }),
        getBotStructuresByBridge: (values) => dispatch({
            type: 'structure/getBotStructuresByBridge',
            payload: values
        }),

    })
)(Form.create('BotComponentForm', {

})(BotComponentForm));